package com.zyl.pagergallery_kt

import android.os.Bundle
import android.os.Handler
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.zyl.pagergallery_kt.adapter.GalleryAdapter
import com.zyl.pagergallery_kt.viewModel.GalleryViewModel
import kotlinx.android.synthetic.main.fragment_gallery.*


class GalleryFragment : Fragment() {
    //lateinit 不能和?=null 一起使用
    private lateinit var galleryViewModel: GalleryViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    //创建菜单Item
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu, menu)
    }

    //选择事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.refresh -> {
                //加上1秒加载这样就用刷新的那个图标
                swipeRefreshLayoutGallery.isRefreshing = true
                Handler().postDelayed({ galleryViewModel.fetchData() }, 1000)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        setHasOptionsMenu(true) //显示菜单 Menu

        //获得ViewModel，因为是AndroidViewModel所以要使用ViewModelProvider.AndroidViewModelFactory来进行创建
        galleryViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(GalleryViewModel::class.java)

        //创建适配器
        val galleryAdapter = GalleryAdapter()


        recyclerViewGallery.apply {
            //设置适配器
            adapter = galleryAdapter
            //设置自适应 2排布局
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }


        //观察ViewModel中的photoListLive，改变了就通知Adapter
        galleryViewModel.photoListLive.observe(this, Observer {
            galleryAdapter.submitList(it)
            swipeRefreshLayoutGallery.isRefreshing = false //不是刷新状态，停止刷新
        })

        //初次刷新
        galleryViewModel.photoListLive.value ?: galleryViewModel.fetchData()

        //界面下滑，刷新事件
        swipeRefreshLayoutGallery.setOnRefreshListener {
            galleryViewModel.fetchData()
        }

    }

}